import tkinter as tk
from tkinter import filedialog
import shutil
import os
import hashlib

def upload_file():
    # 获取用户输入的ID和文件路径
    user_id = user_id_entry.get()
    if not user_id:
        status_label.config(text="请先输入用户ID")
        return

    file_path = filedialog.askopenfilename()
    if file_path:
        # 计算文件哈希值
        hash_value = calculate_hash(file_path)

        index_file = os.path.join(r"E:\A课程资料\应用密码学\EP2", "index.txt")

        # 检查是否有相同哈希值的文件存在
        isSame=update_index_with_duplicates(user_id, hash_value, index_file)

        if isSame!=True:
            # 创建用户文件夹并复制文件
            destination_dir = os.path.join(r"E:\A课程资料\应用密码学\EP2", user_id)
            os.makedirs(destination_dir, exist_ok=True)
            shutil.copy(file_path, destination_dir)
            with open(index_file, "a") as f:
                f.write(f"{user_id}|{os.path.join(destination_dir, os.path.basename(file_path))}|{hash_value}\n")

        # 提示上传成功
        status_label.config(text="文件上传成功")

def update_index_with_duplicates(user_id, hash_value, index_file):
    # 读取index.txt文件
    files_dict = {}
    if os.path.exists(index_file):
        with open(index_file, "r") as f:
            for line in f:
                data = line.strip().split("|")
                if len(data) == 3:
                    files_dict[(data[0], data[2])] = os.path.normpath(data[1])

    # 检查是否有相同哈希值的文件存在，且排除当前用户的记录
    existing_record = (user_id, hash_value)
    existing_file_path = None
    for key, value in files_dict.items():
        if key[1] == hash_value and key != existing_record:
            # 如果存在相同哈希值的文件，更新记录
            existing_file_path = value
            break

    if existing_file_path:
        with open(index_file, "a") as f:
            f.write(f"{user_id}|{existing_file_path}|{hash_value}\n")
        return True
    else:
        print("here")
        return False

def calculate_hash(file_path):
    # 计算文件哈希值
    hasher = hashlib.sha256()
    with open(file_path, 'rb') as f:
        while True:
            data = f.read(65536)  # 64 KB
            if not data:
                break
            hasher.update(data)
    return hasher.hexdigest()






def show_files():
    # 获取用户输入的ID
    user_id = user_id_entry.get()
    if not user_id:
        status_label.config(text="请先输入用户ID")
        return

    # 读取index.txt文件
    index_file = os.path.join(r"E:\A课程资料\应用密码学\EP2", "index.txt")
    files_list = []
    if os.path.exists(index_file):
        with open(index_file, "r") as f:
            for line in f:
                data = line.strip().split("|")
                if len(data) == 3 and data[0] == user_id:
                    files_list.append(data[1])

    # 在显示列表中显示文件名
    files_display.delete(0, tk.END)
    for file_path in files_list:
        file_name = os.path.basename(file_path)
        files_display.insert(tk.END, file_name)

# 创建主窗口
root = tk.Tk()
root.title("文件上传")

# 用户ID输入框
user_id_label = tk.Label(root, text="用户ID：")
user_id_label.grid(row=0, column=0, padx=5, pady=5)
user_id_entry = tk.Entry(root)
user_id_entry.grid(row=0, column=1, padx=5, pady=5)

# 上传按钮
upload_button = tk.Button(root, text="上传文件", command=upload_file)
upload_button.grid(row=1, column=0, padx=5, pady=5)

# 显示文件按钮
show_files_button = tk.Button(root, text="显示文件", command=show_files)
show_files_button.grid(row=1, column=1, padx=5, pady=5)

# 文件显示列表
files_display = tk.Listbox(root)
files_display.grid(row=2, column=0, columnspan=2, padx=5, pady=5)

# 状态提示
status_label = tk.Label(root, text="")
status_label.grid(row=3, column=0, columnspan=2, padx=5, pady=5)

# 运行主事件循环
root.mainloop()
